package com.showsu.editor.manage;


import com.showsu.editor.entity.doo.RemoteInterfaceInfo;
import com.showsu.editor.entity.doo.RemoteInterfaceSwitchRecord;
import com.showsu.editor.entity.doo.SysDict;
import com.showsu.editor.enums.InterfaceSwitchStatusEnum;
import com.showsu.editor.service.IRemoteInterfaceInfoService;
import com.showsu.editor.service.IRemoteInterfaceSwitchRecordService;
import com.showsu.editor.service.ISysDictService;
import com.showsu.editor.utils.Constant;
import com.showsu.editor.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 10:22 上午 2024/3/8
 * @Modified By:
 */
@Component
@Slf4j
public class InterfaceAutoSwitchManager {

    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private IRemoteInterfaceInfoService remoteInterfaceInfoService;

    @Autowired
    private IRemoteInterfaceSwitchRecordService remoteInterfaceSwitchRecordService;

    @Transactional
    public void start(Long interfaceId, String params) {
        try {
            if (interfaceId == null) {
                return;
            }
            //0.检查自动切换的开关是否开启
            SysDict autoSwitch = sysDictService.queryByAppIdAndKey(Constant.system, Constant.interfaceAutoSwitch);
            if (autoSwitch == null
                    || StringUtils.isBlank(autoSwitch.getDictValue())
                    || !autoSwitch.getDictValue().equals(Constant.oneString)) {
                return;
            }
            //1.检查10分钟内是否有未完成的相同切换行为
            RemoteInterfaceSwitchRecord lastSwitchRecord = remoteInterfaceSwitchRecordService.queryLastSwitchRecordByInterfaceId(interfaceId);
            if (lastSwitchRecord != null
                    && !lastSwitchRecord.getStatus().equals(InterfaceSwitchStatusEnum.DONE.getCode())
                    && DateUtil.pastMinutes(lastSwitchRecord.getCreateTime()) < 10) {
                log.info("InterfaceAutoSwitchManager.start(Long,String)已经有相同的任务在跑了，不必要重复发起");
                return;
            }
            //2.检查是否在自动切换的时间段内
            SysDict autoTime = sysDictService.queryByAppIdAndKey(Constant.system, Constant.interfaceAutoTime);
            if (autoTime == null
                    || StringUtils.isBlank(autoTime.getDictValue())
                    || (!DateUtil.checkTimeRangeAvailable(autoTime.getDictValue()))) {
                return;
            }
            //3.检查是否存在可切换的接口
            List<RemoteInterfaceInfo> autoInterfaceInfoList = remoteInterfaceInfoService.queryAutoSwitchInterfacesBySameInterface(interfaceId);
            if (CollectionUtils.isEmpty(autoInterfaceInfoList)) {
                log.info("该接口不存在可自动切换的其他接口，interfaceId:{}", interfaceId);
                return;
            }
            //4.检查是否存在切换中的接口
            RemoteInterfaceSwitchRecord lastRemoteInterfaceSwitchRecord = remoteInterfaceSwitchRecordService.queryLastSwitchRecordByInterfaceName(autoInterfaceInfoList.get(0).getInterfaceName());
            if (lastRemoteInterfaceSwitchRecord != null
                    && DateUtil.pastMinutes(lastRemoteInterfaceSwitchRecord.getCreateTime()) <= 10
                    && !lastRemoteInterfaceSwitchRecord.getStatus().equals(InterfaceSwitchStatusEnum.DONE.getCode())) {
                log.info("接口正在重试中，等待完成....切换中的interfaceId:{}", lastRemoteInterfaceSwitchRecord.getInterfaceId());
                return;
            }
            //5.开始切换
            log.info("InterfaceAutoSwitchManager.start(Long)开始接口切换逻辑");
            RemoteInterfaceInfo remoteInterfaceInfo = remoteInterfaceInfoService.queryById(interfaceId);
            int num = remoteInterfaceSwitchRecordService.add(remoteInterfaceInfo.getInterfaceName(), interfaceId, params);
            if (num == 0) {
                log.info("InterfaceAutoSwitchManager.start(Long,String)接口切换新记录失败，技术快看看怎么回事！，interfaceId:{}", interfaceId);
            } else {
                log.info("InterfaceAutoSwitchManager.start(Long,String)接口切换新记录生成，interfaceId:{}", interfaceId);
            }
        } catch (Exception e) {
            log.error("InterfaceAutoSwitchManager.start(Long,String) error", e);
        }
    }
}
